package server;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Rectangle2D;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class PasswordPanel extends JPanel{
	private static final long serialVersionUID = 1L;
	
	JButton createButton;
	JLabel usernameLabel;
	JTextField usernameField;
	
	private static final String Instructions = "Please specify a username to generate a password.";  
	
	String successOrFailureMessage = Instructions;
	String password = "";
	String username = "";
	
	public PasswordPanel(){
		setLayout(null);
		
		JPanel panel = new JPanel();
		panel.setLayout(new GridLayout(1, 2, 10, 10));
		usernameLabel = new JLabel("Username :", JLabel.RIGHT);
		usernameField = new JTextField();
		panel.add(usernameLabel);
		panel.add(usernameField);
		int panelSizeX = 300;
		int panelSizeY = 30;
		panel.setBounds((500-panelSizeX)/2-30, 20, panelSizeX, panelSizeY);
		add(panel);
		
		createButton = new JButton("Generate");
		add(createButton, BorderLayout.NORTH);
		int buttonSizeX = 200;
		int buttonSizeY = 30;
		createButton.setBounds((500-buttonSizeX)/2, 60, buttonSizeX, buttonSizeY);
		createButton.addActionListener(new ButtonAction());
	}
	
	private void generatePassword(String id){
		username = id;
		int pass = (int) (Math.random()*100000);
		password = pass+"";
		successOrFailureMessage = "";
	}
	
	private class ButtonAction implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent arg0) {
			
			String id = usernameField.getText();
			if(id == null || id.equals("")){
				successOrFailureMessage = "You must specify a username to generate a password!";
			}else{
				generatePassword(id);
				usernameField.setText("");
			}
			repaint();
		}
		
	}
	
	@Override
	public void paintComponent(Graphics g){
		super.paintComponent(g);
		
		g.setColor(Color.gray);
		g.fillRect(0, 110, 600, 3);
		
		if(successOrFailureMessage.equals("")){
			g.setColor(Color.black);
			g.setFont(new Font("MyFont", Font.BOLD, 50));
			g.drawString(("Username  : " + username), 30, 200);
			g.drawString(("Password : " + password), 30, 300);
		}else{
			if(successOrFailureMessage.equals(Instructions)){
				g.setColor(Color.black);
			} else {
				g.setColor(Color.red);
			}
			Rectangle2D rect = g.getFontMetrics().getStringBounds(successOrFailureMessage, g);
			g.setFont(new Font("MyFont2", Font.BOLD, 15));
			g.drawString(successOrFailureMessage, (500-(int)rect.getWidth())/2-18, 200);
		}
		
	}

}
